package com.ck.express.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.ck.express.R
import com.ck.express.databinding.ItemFailedRecordBinding
import com.ck.express.databinding.ItemLoadingBinding
import com.ck.express.enums.RecordTypeEnum
import com.ck.express.vo.FailedRecord

class RecordAdapter(
    private val onRetryClick: (FailedRecord) -> Unit
) : ListAdapter<FailedRecord, RecyclerView.ViewHolder>(DiffCallback) {

    private var isLoading = false

    fun setLoading(loading: Boolean) {
        val previousLoading = isLoading
        isLoading = loading

        if (previousLoading != loading) {
            if (loading) {
                notifyItemInserted(itemCount)
            } else {
                notifyItemRemoved(itemCount)
            }
        }
    }

    override fun getItemCount(): Int {
        return super.getItemCount() + if (isLoading) 1 else 0
    }

    override fun getItemViewType(position: Int): Int {
        return if (isLoading && position == itemCount - 1) {
            VIEW_TYPE_LOADING
        } else {
            VIEW_TYPE_ITEM
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == VIEW_TYPE_ITEM) {
            val binding = ItemFailedRecordBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
            RecordViewHolder(binding)
        } else {
            val binding = ItemLoadingBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
            LoadingViewHolder(binding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is RecordViewHolder && position < super.getItemCount()) {
            holder.bind(getItem(position))
        }
    }

    inner class RecordViewHolder(
        private val binding: ItemFailedRecordBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(record: FailedRecord) {
            binding.apply {
                waybillNo.text = record.waybillNo
                failureReason.text = record.failureReason
                //重试次数
                retryCount.text = "${record.retryCount}次"
                createTime.text = record.createTime

                // 枚举解析（防止崩溃）
                val typeEnum = RecordTypeEnum.from(record.recordType)

                recordTypeText.text = when (typeEnum) {
                    RecordTypeEnum.DELIVERY -> "供件失败"
                    RecordTypeEnum.LATTICE -> "落格失败"
                    null -> ""
                }

                recordTypeIcon.setImageResource(
                    when (typeEnum) {
                        RecordTypeEnum.DELIVERY -> R.drawable.ic_delivery_failed
                        RecordTypeEnum.LATTICE -> R.drawable.ic_lattice_failed
                        null -> 0
                    }
                )

                retryButton.setOnClickListener {
                    onRetryClick(record)
                }
            }
        }
    }

    inner class LoadingViewHolder(binding: ItemLoadingBinding) :
        RecyclerView.ViewHolder(binding.root)

    companion object {
        private const val VIEW_TYPE_ITEM = 0
        private const val VIEW_TYPE_LOADING = 1

        private val DiffCallback = object : DiffUtil.ItemCallback<FailedRecord>() {
            override fun areItemsTheSame(oldItem: FailedRecord, newItem: FailedRecord): Boolean {
                return oldItem.waybillNo == newItem.waybillNo
            }

            override fun areContentsTheSame(oldItem: FailedRecord, newItem: FailedRecord): Boolean {
                return oldItem == newItem
            }
        }
    }
}
